package jeecg.business.util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.zip.GZIPInputStream;

import jodd.util.StringUtil;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.jeecgframework.core.util.ResourceUtil;
/**
 * 
 * <p>
 * 标题: 短信 工具类 
 * </p>
 * <p>
 * 描述: // TODO
 * </p>
 * 
 * @author LinYingPiaoJian(Q:71426052)
 * @version // TODO
 * @since 2015-1-31 下午4:24:01
 */
public class SmsUtil {
	static String user = ResourceUtil.getSessionattachmenttitle("sms.user");
	static String pwd = ResourceUtil.getSessionattachmenttitle("sms.pwd");
	
	public static void sendSms(String mobile , String content){
		if(StringUtil.isEmpty(mobile)) return ;
		HttpParams httpParams = new BasicHttpParams(); 
		httpParams.setParameter("charset", "UTF-8"); 
		DefaultHttpClient httpclient = new DefaultHttpClient(httpParams);	
		String postStr = "u="+user+"&p="+encryption(pwd)+"&m="+mobile+"&c="+content;
		HttpPost post = new HttpPost("http://api.smsbao.com/sms?"+postStr);
		try{
			post.addHeader("User-Agent","Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)");
			post.addHeader("Accept", "text/html, application/xhtml+xml");
			post.addHeader("Accept-Language", "zh-CN");
			post.addHeader("Accept-Encoding", "gzip, deflate");
			post.addHeader("Connection", "Keep-Alive");
			post.addHeader("Cache-Control", "no-cache");
			post.addHeader("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");
			
			//content = "【在南京】"+content;
			
			//content += "，您正在进行手机解绑，如非本人操作，请忽略此短信。";	//测试时需要添加
			
			StringEntity se = new StringEntity("","UTF-8");
			se.setContentEncoding("UTF-8");    
		    se.setContentType("application/x-www-form-urlencoded;charset=UTF-8");
		    post.setEntity(se);	
	        
	        HttpResponse resp5 = httpclient.execute(post);
			InputStream in = resp5.getEntity().getContent();
			String searchResultHtml = uncompress(in, "UTF-8");
			System.out.println("短信发送："+"http://api.smsbao.com/sms?"+postStr);
			System.out.println("返回结果："+searchResultHtml);
			
		}catch(Exception e){
			e.printStackTrace();
			throw new RuntimeException("发送短信失败");
		}finally{
			// 释放get5
			post.releaseConnection();
			httpclient.getConnectionManager().shutdown();
			httpclient.close();
		}
	}
	
	/** 
	 * 解开GZIP压缩的网页内容
	*/
	public static String uncompress(InputStream in, String charset) {
		try {
			GZIPInputStream gInputStream = new GZIPInputStream(in);
			byte[] by = new byte[1024];
			StringBuffer strBuffer = new StringBuffer();
			int len = 0;
			while ((len = gInputStream.read(by)) != -1) {
				strBuffer.append(new String(by, 0, len, charset));
			}
			return strBuffer.toString();
		} catch (Exception e) {
			String backStr = "";
			try {
				BufferedReader reader = new BufferedReader(new InputStreamReader(in, charset));
				String line = null;
				while ((line = reader.readLine()) != null) {
					backStr += line;
				}
			} catch (Exception e1) {
				e1.printStackTrace();
			}
			
			return backStr;
		}
	}	
	
	public static String encryption(String plainText) {
        String re_md5 = new String();
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(plainText.getBytes());
            byte b[] = md.digest();
 
            int i;
 
            StringBuffer buf = new StringBuffer("");
            for (int offset = 0; offset < b.length; offset++) {
                i = b[offset];
                if (i < 0)
                    i += 256;
                if (i < 16)
                    buf.append("0");
                buf.append(Integer.toHexString(i));
            }
 
            re_md5 = buf.toString();
 
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return re_md5;
    }

	
	public static void main(String[] args) {
//		System.out.println();
		sendSms("18759512152,13459463979", "群发短信!");
		
	}
}
